import React, { useState, useEffect, useRef } from "react";
import "./Createdesign.css";
import { Input, Image, Row, Col, Spin, message, Modal, Select, ColorPicker, Slider, Radio, Space, Button } from "antd";
import axios from "axios";
import Cropper from 'react-cropper';
import type { ReactCropperElement } from 'react-cropper';
import 'cropperjs/dist/cropper.css';
import { removeBackground } from '@imgly/background-removal';

/**
 * 定义抽屉内容类型枚举
 * 包含所有可能的抽屉类型
 */
type DrawerContentType =
  | "添加"
  | "模板"
  | "元素"
  | "文字"
  | "图片"
  | "背景"
  | "AI工具"
  | "品牌"
  | "团队"
  | "我的"
  | "分享管理"
  | "";

/**
 * 定义抽屉项的数据结构
 * 用于描述抽屉中的每个项目
 */
interface DrawerItem {
  id: string; // 项目唯一标识
  name: string; // 项目显示名称
  icon?: string; // 可选图标
  category?: string; // 可选分类
}

/**
 * 定义图片项的数据结构
 * 用于描述从后端获取的图片数据
 */
interface ImageItem {
  id: number; // 图片ID
  img: string; // 图片URL
  title?: string; // 可选标题
  description?: string; // 可选描述
  created_at?: string; // 可选创建时间
  updated_at?: string; // 可选更新时间
  isShared?: boolean; // 添加分享状态
}

/**
 * 定义文字项的数据结构
 */
type TextAlign = "left" | "center" | "right";
type TextEffect = "none" | "glow" | "neon" | "metal" | "gradient" | "3d";

interface TextItem {
  id: string;
  content: string;
  position: { x: number; y: number };
  style: {
    fontSize: number;
    fontFamily: string;
    color: string;
    fontWeight: string;
    fontStyle: string;
    textAlign: TextAlign;
    textDecoration: string;
    letterSpacing: number;
    lineHeight: number;
    opacity: number;
    rotate: number;
    shadow: {
      color: string;
      blur: number;
      offsetX: number;
      offsetY: number;
    };
    stroke: {
      color: string;
      width: number;
    };
    effect: TextEffect;
    background?: string;
    WebkitBackgroundClip?: string;
    WebkitTextFillColor?: string;
  };
}

// 从Ant Design解构Search组件
const { Search } = Input;

/**
 * 定义缩放控制点类型
 * 包含8个可能的控制点位置（四边和四角）
 */
type ResizeHandle =
  | "top"
  | "right"
  | "bottom"
  | "left"
  | "top-left"
  | "top-right"
  | "bottom-left"
  | "bottom-right"
  | "";

/**
 * 设计页面主组件
 * 功能：
 * 1. 左侧操作栏：提供各种设计工具和功能入口
 * 2. 中间画布区域：显示和编辑设计内容
 * 3. 右侧属性面板：编辑选中元素的属性
 * 4. 图片操作：支持拖拽、缩放、裁剪、背景移除等
 * 5. 文字操作：支持添加、编辑、移动文字
 * 6. 模板管理：从后端获取和管理设计模板
 */
const Createdesign: React.FC = () => {
  // ========== 状态管理 ==========

  /**
   * 抽屉相关状态
   * drawerOpen: 控制抽屉是否打开
   * activeDrawer: 当前打开的抽屉类型
   * searchText: 搜索框文本
   */
  const [drawerOpen, setDrawerOpen] = useState<boolean>(false);
  const [activeDrawer, setActiveDrawer] = useState<DrawerContentType>("");
  const [searchText, setSearchText] = useState<string>("");

  /**
   * 数据加载状态
   * loading: 是否正在加载数据
   * error: 错误信息
   * backendImages: 从后端获取的图片数据
   */
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [backendImages, setBackendImages] = useState<ImageItem[]>([]);

  /**
   * 图片相关状态
   * selectedImage: 当前选中的图片URL
   * imagePosition: 图片在画布中的位置
   * imageSize: 图片当前尺寸
   * naturalSize: 图片原始尺寸
   * canvasSize: 画布尺寸
   * imageOpacity: 图片透明度
   */
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [imagePosition, setImagePosition] = useState({ x: 0, y: 0 });
  const [imageSize, setImageSize] = useState({ width: 0, height: 0 });
  const [naturalSize, setNaturalSize] = useState({ width: 0, height: 0 });
  const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 });
  const [imageOpacity, setImageOpacity] = useState(1);

  /**
   * 交互状态
   * isDragging: 是否正在拖拽
   * isResizing: 是否正在缩放
   * resizeHandle: 当前操作的缩放控制点
   */
  const [isDragging, setIsDragging] = useState(false);
  const [isResizing, setIsResizing] = useState(false);
  const [resizeHandle, setResizeHandle] = useState<ResizeHandle>("");

  /**
   * 右侧面板编辑状态
   * isEditingWidth/Height: 是否正在编辑宽度/高度
   * tempWidth/Height: 临时存储编辑中的宽度/高度值
   */
  const [isEditingWidth, setIsEditingWidth] = useState(false);
  const [isEditingHeight, setIsEditingHeight] = useState(false);
  const [tempWidth, setTempWidth] = useState("");
  const [tempHeight, setTempHeight] = useState("");

  /**
   * 记录交互开始状态
   * startPos: 开始拖拽时的位置
   */
  const [startPos, setStartPos] = useState({ x: 0, y: 0 });

  /**
   * Refs
   * canvasRef: 画布DOM引用
   * imgElementRef: 图片元素DOM引用
   */
  const canvasRef = useRef<HTMLDivElement>(null);
  const imgElementRef = useRef<HTMLImageElement>(null);

  /**
   * 裁剪相关状态
   * isCropperVisible: 裁剪模态框是否可见
   * cropperRef: 裁剪器组件引用
   */
  const [isCropperVisible, setIsCropperVisible] = useState(false);
  const cropperRef = useRef<ReactCropperElement>(null);

  /**
   * 文字相关状态
   * textItems: 所有文字项
   * selectedTextId: 当前选中的文字ID
   * isAddingText: 是否正在添加文字
   * textContent: 新文字内容
   * textStyle: 文字样式
   */
  const [textItems, setTextItems] = useState<TextItem[]>([]);
  const [selectedTextId, setSelectedTextId] = useState<string | null>(null);
  const [isAddingText, setIsAddingText] = useState(false);
  const [textContent, setTextContent] = useState("");
  const [textStyle, setTextStyle] = useState<TextItem["style"]>({
    fontSize: 16,
    fontFamily: "Arial",
    color: "#000000",
    fontWeight: "normal",
    fontStyle: "normal",
    textAlign: "left",
    textDecoration: "none",
    letterSpacing: 0,
    lineHeight: 1.5,
    opacity: 1,
    rotate: 0,
    shadow: {
      color: "#000000",
      blur: 0,
      offsetX: 0,
      offsetY: 0,
    },
    stroke: {
      color: "#000000",
      width: 0,
    },
    effect: "none",
  });

  // 字体选项
  const fontFamilies = [
    { label: "Arial", value: "Arial" },
    { label: "Times New Roman", value: "Times New Roman" },
    { label: "微软雅黑", value: "Microsoft YaHei" },
    { label: "宋体", value: "SimSun" },
    { label: "黑体", value: "SimHei" },
    { label: "楷体", value: "KaiTi" },
    { label: "仿宋", value: "FangSong" },
    { label: "幼圆", value: "YouYuan" },
    { label: "华文黑体", value: "STHeiti" },
    { label: "华文楷体", value: "STKaiti" },
    { label: "华文宋体", value: "STSong" },
    { label: "华文仿宋", value: "STFangsong" },
    { label: "华文中宋", value: "STZhongsong" },
    { label: "华文琥珀", value: "STHupo" },
    { label: "华文新魏", value: "STXinwei" },
    { label: "华文隶书", value: "STLiti" },
    { label: "华文行楷", value: "STXingkai" },
    { label: "华文彩云", value: "STCaiyun" },
  ];

  // 文字对齐方式
  const textAlignOptions = [
    { label: "左对齐", value: "left" },
    { label: "居中", value: "center" },
    { label: "右对齐", value: "right" },
  ];

  // 文字特效选项
  const textEffects = [
    { label: "无特效", value: "none" as TextEffect },
    { label: "发光", value: "glow" as TextEffect },
    { label: "霓虹", value: "neon" as TextEffect },
    { label: "金属", value: "metal" as TextEffect },
    { label: "渐变", value: "gradient" as TextEffect },
    { label: "3D", value: "3d" as TextEffect },
  ];

  // 新增拖动文字的状态
  const [draggingTextId, setDraggingTextId] = useState<string | null>(null);
  const [textDragOffset, setTextDragOffset] = useState({ x: 0, y: 0 });

  // 添加背景移除相关状态
  const [isRemovingBackground, setIsRemovingBackground] = useState(false);
  const [originalImage, setOriginalImage] = useState<string | null>(null);
  const [removalProgress, setRemovalProgress] = useState(0);

  // 添加拖拽相关状态
  const [isDraggingOver, setIsDraggingOver] = useState(false);

  // 添加下载相关状态
  const [isDownloading, setIsDownloading] = useState(false);

  // 添加图片选中状态
  const [selectedElement, setSelectedElement] = useState<'image' | 'text' | null>(null);

  // 添加分享管理相关状态
  const [sharedImages, setSharedImages] = useState<ImageItem[]>([]);
  const [hoveredImageId, setHoveredImageId] = useState<number | null>(null);

  // ========== 模拟数据 ===========

  /**
   * 抽屉项目数据
   * 包含所有抽屉类型的初始数据
   */
  const [drawerItems] = useState<Record<DrawerContentType, DrawerItem[]>>({
    添加: [
      { id: "add-1", name: "图片", category: "媒体" },
      { id: "add-2", name: "视频", category: "媒体" },
      { id: "add-3", name: "形状", category: "基础" },
    ],
    模板: [], // 清空模拟数据，使用从后端获取的真实数据
    元素: [
      { id: "el-1", name: "图标", category: "基础" },
      { id: "el-2", name: "装饰", category: "样式" },
    ],
    文字: [
      { id: "text-add", name: "添加文字", category: "基础" },
      { id: "text-title", name: "标题文字", category: "预设" },
      { id: "text-subtitle", name: "副标题", category: "预设" },
      { id: "text-body", name: "正文文字", category: "预设" },
      { id: "text-quote", name: "引用文字", category: "预设" },
    ],
    图片: [
      { id: "img-1", name: "风景图片" },
      { id: "img-2", name: "人物图片" },
    ],
    背景: [
      { id: "bg-1", name: "纯色背景" },
      { id: "bg-2", name: "纹理背景" },
    ],
    AI工具: [
      { id: "ai-1", name: "图像生成" },
      { id: "ai-2", name: "文字排版" },
    ],
    品牌: [
      { id: "brand-1", name: "品牌logo" },
      { id: "brand-2", name: "品牌色板" },
    ],
    团队: [
      { id: "team-1", name: "团队成员" },
      { id: "team-2", name: "团队项目" },
    ],
    我的: [
      { id: "my-1", name: "我的收藏" },
      { id: "my-2", name: "我的作品" },
    ],
    "分享管理": [],
    "": [],
  });

  // ========== 生命周期和副作用 ==========

  /**
   * 监听画布尺寸变化
   * 当画布尺寸改变时，重新计算图片位置使其居中
   */
  useEffect(() => {
    const updateCanvasSize = () => {
      if (canvasRef.current) {
        const rect = canvasRef.current.getBoundingClientRect();
        setCanvasSize({
          width: rect.width,
          height: rect.height,
        });

        // 如果已有选中图片，重新计算居中位置
        if (selectedImage) {
          const centerX = (rect.width - imageSize.width) / 2;
          const centerY = (rect.height - imageSize.height) / 2;
          setImagePosition({
            x: Math.max(0, centerX),
            y: Math.max(0, centerY),
          });
        }
      }
    };

    updateCanvasSize();
    window.addEventListener("resize", updateCanvasSize);

    return () => {
      window.removeEventListener("resize", updateCanvasSize);
    };
  }, [selectedImage, imageSize.width, imageSize.height]);

  /**
   * 从后端获取图片数据
   * 当打开模板抽屉时触发
   */
  const getBackendImages = async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await axios.get("http://localhost:3000/api/images");
      setBackendImages(res.data);
    } catch (error) {
      console.error("获取图片失败:", error);
      setError("加载模板图片失败，请稍后重试");
      message.error("加载模板图片失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (activeDrawer === "模板") {
      getBackendImages();
    }
  }, [activeDrawer]);

  // ========== 图片交互逻辑 ==========

  /**
   * 处理图片加载完成
   * 计算图片初始尺寸和位置
   */
  const handleImageLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
    const img = e.target as HTMLImageElement;
    const naturalWidth = img.naturalWidth;
    const naturalHeight = img.naturalHeight;

    setNaturalSize({
      width: naturalWidth,
      height: naturalHeight,
    });

    // 计算初始尺寸（限制在画布范围内）
    let initialWidth = naturalWidth;
    let initialHeight = naturalHeight;

    if (canvasSize.width > 0 && canvasSize.height > 0) {
      const widthRatio = canvasSize.width / naturalWidth;
      const heightRatio = canvasSize.height / naturalHeight;
      const minRatio = Math.min(widthRatio, heightRatio, 1); // 不超过原始大小

      initialWidth = naturalWidth * minRatio;
      initialHeight = naturalHeight * minRatio;
    }

    setImageSize({
      width: initialWidth,
      height: initialHeight,
    });

    // 计算居中位置
    const centerX = (canvasSize.width - initialWidth) / 2;
    const centerY = (canvasSize.height - initialHeight) / 2;

    setImagePosition({
      x: Math.max(0, centerX),
      y: Math.max(0, centerY),
    });
  };

  /**
   * 开始拖拽图片
   * @param e 鼠标按下事件
   */
  const handleDragStart = (e: React.MouseEvent) => {
    if (!selectedImage || isResizing) return;

    setIsDragging(true);
    setStartPos({
      x: e.clientX - imagePosition.x,
      y: e.clientY - imagePosition.y,
    });
    document.body.style.userSelect = "none";
  };

  /**
   * 处理缩放开始
   * @param e 鼠标按下事件
   * @param handle 缩放控制点类型
   */
  const handleResizeStart = (e: React.MouseEvent, handle: ResizeHandle) => {
    e.stopPropagation();
    if (!selectedImage) return;

    setIsResizing(true);
    setResizeHandle(handle);
    setStartPos({ x: e.clientX, y: e.clientY });
    document.body.style.userSelect = "none";
  };

  /**
   * 处理鼠标移动事件
   * 同时处理拖拽和缩放逻辑
   * @param e 鼠标移动事件
   */
  const handleMouseMove = (e: React.MouseEvent) => {
    if (!selectedImage || !canvasRef.current) return;

    // 处理拖拽逻辑
    if (isDragging) {
      const newX = e.clientX - startPos.x;
      const newY = e.clientY - startPos.y;

      setImagePosition({
        x: newX,
        y: newY,
      });
      return;
    }

    // 处理缩放逻辑
    if (isResizing) {
      const deltaX = e.clientX - startPos.x;
      const deltaY = e.clientY - startPos.y;

      let newWidth = imageSize.width;
      let newHeight = imageSize.height;
      let newX = imagePosition.x;
      let newY = imagePosition.y;

      // 根据控制点类型处理缩放
      switch (resizeHandle) {
        case "top":
          newHeight = Math.max(20, imageSize.height - deltaY);
          newY = imagePosition.y + (imageSize.height - newHeight);
          break;

        case "top-left":
          newWidth = Math.max(20, imageSize.width - deltaX);
          newHeight = Math.max(20, imageSize.height - deltaY);
          newX = imagePosition.x + (imageSize.width - newWidth);
          newY = imagePosition.y + (imageSize.height - newHeight);
          break;

        case "top-right":
          newWidth = Math.max(20, imageSize.width + deltaX);
          newHeight = Math.max(20, imageSize.height - deltaY);
          newY = imagePosition.y + (imageSize.height - newHeight);
          break;

        case "bottom":
          newHeight = Math.max(20, imageSize.height + deltaY);
          break;

        case "bottom-left":
          newWidth = Math.max(20, imageSize.width - deltaX);
          newHeight = Math.max(20, imageSize.height + deltaY);
          newX = imagePosition.x + (imageSize.width - newWidth);
          break;

        case "bottom-right":
          newWidth = Math.max(20, imageSize.width + deltaX);
          newHeight = Math.max(20, imageSize.height + deltaY);
          break;

        case "left":
          newWidth = Math.max(20, imageSize.width - deltaX);
          newX = imagePosition.x + (imageSize.width - newWidth);
          break;

        case "right":
          newWidth = Math.max(20, imageSize.width + deltaX);
          break;
      }

      setImageSize({
        width: newWidth,
        height: newHeight,
      });

      setImagePosition({
        x: newX,
        y: newY,
      });

      // 更新起始位置和尺寸
      setStartPos({ x: e.clientX, y: e.clientY });
    }
  };

  /**
   * 结束交互（拖拽或缩放）
   */
  const handleMouseUp = () => {
    setIsDragging(false);
    setIsResizing(false);
    setResizeHandle("");
    document.body.style.userSelect = "";
  };

  /**
   * 鼠标离开画布时结束交互
   */
  const handleMouseLeave = () => {
    if (isDragging || isResizing) {
      handleMouseUp();
    }
  };

  /**
   * 重置图片位置和大小到初始状态
   */
  const resetImage = () => {
    if (!imgElementRef.current || !canvasRef.current) return;

    const img = imgElementRef.current;
    const canvasRect = canvasRef.current.getBoundingClientRect();

    // 计算初始尺寸（限制在画布范围内）
    let initialWidth = img.naturalWidth;
    let initialHeight = img.naturalHeight;

    const widthRatio = canvasRect.width / img.naturalWidth;
    const heightRatio = canvasRect.height / img.naturalHeight;
    const minRatio = Math.min(widthRatio, heightRatio, 1); // 不超过原始大小

    initialWidth = img.naturalWidth * minRatio;
    initialHeight = img.naturalHeight * minRatio;

    setImageSize({
      width: initialWidth,
      height: initialHeight,
    });

    // 计算居中位置
    const centerX = (canvasRect.width - initialWidth) / 2;
    const centerY = (canvasRect.height - initialHeight) / 2;

    setImagePosition({
      x: Math.max(0, centerX),
      y: Math.max(0, centerY),
    });
  };

  /**
   * 选择图片时重置状态
   * @param img 图片URL
   */
  const handleSelectImage = (img: string) => {
    setSelectedImage(img);
    // 图片加载后会通过handleImageLoad自动居中
  };

  // ========== 右侧面板编辑功能 ==========

  /**
   * 处理宽度输入框变化
   * @param e 输入事件
   */
  const handleWidthChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setTempWidth(e.target.value);
  };

  /**
   * 处理高度输入框变化
   * @param e 输入事件
   */
  const handleHeightChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setTempHeight(e.target.value);
  };

  /**
   * 开始编辑宽度
   */
  const startEditingWidth = () => {
    setIsEditingWidth(true);
    setTempWidth(Math.round(imageSize.width).toString());
  };

  /**
   * 开始编辑高度
   */
  const startEditingHeight = () => {
    setIsEditingHeight(true);
    setTempHeight(Math.round(imageSize.height).toString());
  };

  /**
   * 提交宽度修改
   */
  const submitWidthChange = () => {
    const newWidth = parseInt(tempWidth);
    if (!isNaN(newWidth) && newWidth > 0) {
      setImageSize({
        width: newWidth,
        height: imageSize.height, // 保持高度不变
      });
    }
    setIsEditingWidth(false);
  };

  /**
   * 提交高度修改
   */
  const submitHeightChange = () => {
    const newHeight = parseInt(tempHeight);
    if (!isNaN(newHeight) && newHeight > 0) {
      setImageSize({
        width: imageSize.width, // 保持宽度不变
        height: newHeight,
      });
    }
    setIsEditingHeight(false);
  };

  /**
   * 处理键盘事件（回车提交，ESC取消）
   * @param e 键盘事件
   * @param type 编辑类型（'width' | 'height'）
   */
  const handleKeyDown = (e: React.KeyboardEvent, type: "width" | "height") => {
    if (e.key === "Enter") {
      if (type === "width") {
        submitWidthChange();
      } else {
        submitHeightChange();
      }
    } else if (e.key === "Escape") {
      if (type === "width") {
        setIsEditingWidth(false);
      } else {
        setIsEditingHeight(false);
      }
    }
  };

  // ========== 搜索功能 ==========

  /**
   * 处理搜索输入变化
   * @param e 输入事件
   */
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchText(e.target.value);
  };

  /**
   * 处理搜索提交
   * @param value 搜索关键词
   */
  const handleSearch = (value: string) => {
    console.log("搜索关键词:", value);
    // 实际项目中这里可以添加更复杂的过滤逻辑或API请求
  };

  // ========== 抽屉功能 ==========

  /**
   * 切换抽屉状态
   * @param drawerType 要打开的抽屉类型
   */
  const handleToggleDrawer = (drawerType: DrawerContentType) => {
    if (activeDrawer === drawerType) {
      // 点击当前已打开的抽屉，则关闭
      setDrawerOpen(false);
      setActiveDrawer("");
    } else {
      // 打开新抽屉
      setActiveDrawer(drawerType);
      setDrawerOpen(true);
    }
    setSearchText(""); // 清空搜索
  };

  // ========== 渲染方法 ==========

  /**
   * 渲染缩放控制点
   */
  const renderResizeHandles = () => {
    if (!selectedImage) return null;

    const { width, height } = imageSize;
    const handleSize = 8;
    const halfHandle = handleSize / 2;

    return (
      <>
        {/* 四边控制点 */}
        <div
          className="resize-handle top"
          style={{
            top: -halfHandle,
            left: width / 2 - halfHandle,
            width: handleSize,
            height: handleSize,
          }}
          onMouseDown={(e) => handleResizeStart(e, "top")}
        />
        <div
          className="resize-handle right"
          style={{
            top: height / 2 - halfHandle,
            left: width - halfHandle,
            width: handleSize,
            height: handleSize,
          }}
          onMouseDown={(e) => handleResizeStart(e, "right")}
        />
        <div
          className="resize-handle bottom"
          style={{
            top: height - halfHandle,
            left: width / 2 - halfHandle,
            width: handleSize,
            height: handleSize,
          }}
          onMouseDown={(e) => handleResizeStart(e, "bottom")}
        />
        <div
          className="resize-handle left"
          style={{
            top: height / 2 - halfHandle,
            left: -halfHandle,
            width: handleSize,
            height: handleSize,
          }}
          onMouseDown={(e) => handleResizeStart(e, "left")}
        />

        {/* 四角控制点 */}
        <div
          className="resize-handle top-left"
          style={{
            top: -halfHandle,
            left: -halfHandle,
            width: handleSize,
            height: handleSize,
          }}
          onMouseDown={(e) => handleResizeStart(e, "top-left")}
        />
        <div
          className="resize-handle top-right"
          style={{
            top: -halfHandle,
            left: width - halfHandle,
            width: handleSize,
            height: handleSize,
          }}
          onMouseDown={(e) => handleResizeStart(e, "top-right")}
        />
        <div
          className="resize-handle bottom-right"
          style={{
            top: height - halfHandle,
            left: width - halfHandle,
            width: handleSize,
            height: handleSize,
          }}
          onMouseDown={(e) => handleResizeStart(e, "bottom-right")}
        />
        <div
          className="resize-handle bottom-left"
          style={{
            top: height - halfHandle,
            left: -halfHandle,
            width: handleSize,
            height: handleSize,
          }}
          onMouseDown={(e) => handleResizeStart(e, "bottom-left")}
        />
      </>
    );
  };

  /**
   * 渲染模板图片内容
   */
  const renderTemplateContent = () => {
    const filteredImages = backendImages.filter((image) => {
      const searchLower = searchText.toLowerCase();
      const url = image.img?.toLowerCase() || "";
      const title = image.title?.toLowerCase() || "";
      const description = image.description?.toLowerCase() || "";

      return (
        url.includes(searchLower) ||
        title.includes(searchLower) ||
        description.includes(searchLower)
      );
    });

    if (loading) {
      return (
        <div className="loading-container">
          <Spin tip="加载中..." size="large" />
        </div>
      );
    }

    if (error) {
      return (
        <div className="error-message">
          {error}
          <button onClick={() => getBackendImages()} className="retry-button">
            重试
          </button>
        </div>
      );
    }

    if (filteredImages.length === 0) {
      return (
        <div className="empty-message">
          {searchText ? "没有找到匹配的模板" : "暂无模板数据"}
        </div>
      );
    }

    return (
      <Row gutter={[16, 16]} className="template-grid">
        {filteredImages.map((image) => (
          <Col span={12} key={image.id} className="template-col">
            <div
              className="template-item"
              onClick={() => handleSelectImage(image.img)}
              onMouseEnter={() => setHoveredImageId(image.id)}
              onMouseLeave={() => setHoveredImageId(null)}
              style={{ position: 'relative' }}
            >
              <Image
                src={image.img || undefined}
                alt={image.title || "模板图片"}
                preview={false}
                className="template-image"
                fallback="https://via.placeholder.com/150?text=图片加载失败"
              />
              <div className="template-info">
                <div className="template-title" title={image.title}>
                  {image.title || `模板-${image.id}`}
                </div>
                {image.description && (
                  <div
                    className="template-description"
                    title={image.description}
                  >
                    {image.description}
                  </div>
                )}
                <div className="template-meta">
                  {image.created_at && (
                    <span>
                      创建: {new Date(image.created_at).toLocaleDateString()}
                    </span>
                  )}
                </div>
              </div>
              {hoveredImageId === image.id && (
                <div
                  className="share-button"
                  onClick={(e) => {
                    e.stopPropagation();
                    handleShareImage(image);
                  }}
                  style={{
                    position: 'absolute',
                    bottom: '10px',
                    right: '10px',
                    background: '#1890ff',
                    color: 'white',
                    padding: '4px 8px',
                    borderRadius: '4px',
                    cursor: 'pointer',
                    zIndex: 1,
                  }}
                >
                  {image.isShared ? '取消分享' : '分享'}
                </div>
              )}
            </div>
          </Col>
        ))}
      </Row>
    );
  };

  /**
   * 渲染文字编辑面板
   */
  const renderTextEditPanel = () => {
    if (!selectedTextId) return null;

    const selectedText = textItems.find(item => item.id === selectedTextId);
    if (!selectedText) return null;

    return (
      <div className="text-edit-panel">
        <div className="property-item">
          <label>文字内容</label>
          <Input.TextArea
            value={selectedText.content}
            onChange={(e) => {
              setTextItems(textItems.map(item => {
                if (item.id === selectedTextId) {
                  return { ...item, content: e.target.value };
                }
                return item;
              }));
            }}
            rows={3}
          />
        </div>

        <div className="property-item">
          <label>字体</label>
          <Select
            value={selectedText.style.fontFamily}
            onChange={(value) => handleTextStyleChange("fontFamily", value)}
            options={fontFamilies}
            style={{ width: "100%" }}
          />
        </div>

        <div className="property-item">
          <label>字号</label>
          <Input
            type="number"
            value={selectedText.style.fontSize}
            onChange={(e) => handleTextStyleChange("fontSize", parseInt(e.target.value))}
            suffix="px"
          />
        </div>

        <div className="property-item">
          <label>颜色</label>
          <ColorPicker
            value={selectedText.style.color}
            onChange={(color) => handleTextStyleChange("color", color.toHexString())}
          />
        </div>

        <div className="property-item">
          <label>字重</label>
          <Radio.Group
            value={selectedText.style.fontWeight}
            onChange={(e) => handleTextStyleChange("fontWeight", e.target.value)}
          >
            <Radio.Button value="normal">常规</Radio.Button>
            <Radio.Button value="bold">粗体</Radio.Button>
          </Radio.Group>
        </div>

        <div className="property-item">
          <label>样式</label>
          <Space>
            <Button
              type={selectedText.style.fontStyle === "italic" ? "primary" : "default"}
              onClick={() => handleTextStyleChange("fontStyle", 
                selectedText.style.fontStyle === "italic" ? "normal" : "italic"
              )}
            >
              斜体
            </Button>
            <Button
              type={selectedText.style.textDecoration === "underline" ? "primary" : "default"}
              onClick={() => handleTextStyleChange("textDecoration",
                selectedText.style.textDecoration === "underline" ? "none" : "underline"
              )}
            >
              下划线
            </Button>
          </Space>
        </div>

        <div className="property-item">
          <label>对齐方式</label>
          <Radio.Group
            value={selectedText.style.textAlign}
            onChange={(e) => handleTextStyleChange("textAlign", e.target.value)}
          >
            {textAlignOptions.map(option => (
              <Radio.Button key={option.value} value={option.value}>
                {option.label}
              </Radio.Button>
            ))}
          </Radio.Group>
        </div>

        <div className="property-item">
          <label>字间距</label>
          <Slider
            min={-5}
            max={20}
            value={selectedText.style.letterSpacing}
            onChange={(value) => handleTextStyleChange("letterSpacing", value)}
          />
        </div>

        <div className="property-item">
          <label>行高</label>
          <Slider
            min={1}
            max={3}
            step={0.1}
            value={selectedText.style.lineHeight}
            onChange={(value) => handleTextStyleChange("lineHeight", value)}
          />
        </div>

        <div className="property-item">
          <label>透明度</label>
          <Slider
            min={0}
            max={1}
            step={0.1}
            value={selectedText.style.opacity}
            onChange={(value) => handleTextStyleChange("opacity", value)}
          />
        </div>

        <div className="property-item">
          <label>旋转角度</label>
          <Slider
            min={-180}
            max={180}
            value={selectedText.style.rotate}
            onChange={(value) => handleTextStyleChange("rotate", value)}
          />
        </div>

        <div className="property-item">
          <label>文字阴影</label>
          <div style={{ marginBottom: 8 }}>
            <label>阴影颜色</label>
            <ColorPicker
              value={selectedText.style.shadow.color}
              onChange={(color) => handleTextStyleChange("shadow", {
                ...selectedText.style.shadow,
                color: color.toHexString(),
              })}
            />
          </div>
          <div style={{ marginBottom: 8 }}>
            <label>模糊程度</label>
            <Slider
              min={0}
              max={20}
              value={selectedText.style.shadow.blur}
              onChange={(value) => handleTextStyleChange("shadow", {
                ...selectedText.style.shadow,
                blur: value,
              })}
            />
          </div>
          <div style={{ marginBottom: 8 }}>
            <label>X偏移</label>
            <Slider
              min={-20}
              max={20}
              value={selectedText.style.shadow.offsetX}
              onChange={(value) => handleTextStyleChange("shadow", {
                ...selectedText.style.shadow,
                offsetX: value,
              })}
            />
          </div>
          <div style={{ marginBottom: 8 }}>
            <label>Y偏移</label>
            <Slider
              min={-20}
              max={20}
              value={selectedText.style.shadow.offsetY}
              onChange={(value) => handleTextStyleChange("shadow", {
                ...selectedText.style.shadow,
                offsetY: value,
              })}
            />
          </div>
        </div>

        <div className="property-item">
          <label>文字描边</label>
          <div style={{ marginBottom: 8 }}>
            <label>描边颜色</label>
            <ColorPicker
              value={selectedText.style.stroke.color}
              onChange={(color) => handleTextStyleChange("stroke", {
                ...selectedText.style.stroke,
                color: color.toHexString(),
              })}
            />
          </div>
          <div style={{ marginBottom: 8 }}>
            <label>描边宽度</label>
            <Slider
              min={0}
              max={10}
              value={selectedText.style.stroke.width}
              onChange={(value) => handleTextStyleChange("stroke", {
                ...selectedText.style.stroke,
                width: value,
              })}
            />
          </div>
        </div>

        <div className="property-item">
          <label>文字特效</label>
          <Select
            value={selectedText.style.effect}
            onChange={(value) => handleTextStyleChange("effect", value as TextEffect)}
            options={textEffects}
            style={{ width: "100%" }}
          />
        </div>

        <div className="property-item">
          <Button type="primary" danger onClick={handleDeleteText}>
            删除文字
          </Button>
        </div>
      </div>
    );
  };

  /**
   * 渲染文字抽屉内容
   */
  const renderTextDrawerContent = () => {
    return (
      <div className="drawer-items-list">
        {drawerItems["文字"].map((item) => (
          <div
            key={item.id}
            className="drawer-item"
            onClick={() => {
              if (item.id === "text-add") {
                setIsAddingText(true);
                setDrawerOpen(false);
              } else {
                // 使用预设样式添加文字
                const presetStyles = {
                  "text-title": {
                    ...textStyle,
                    fontSize: 32,
                    fontWeight: "bold",
                  },
                  "text-subtitle": {
                    ...textStyle,
                    fontSize: 24,
                    fontWeight: "bold",
                  },
                  "text-body": {
                    ...textStyle,
                    fontSize: 16,
                    lineHeight: 1.6,
                  },
                  "text-quote": {
                    ...textStyle,
                    fontSize: 18,
                    fontStyle: "italic",
                    color: "#666666",
                  },
                };

                const newText: TextItem = {
                  id: Date.now().toString(),
                  content: item.name,
                  position: { x: 100, y: 100 },
                  style: presetStyles[item.id as keyof typeof presetStyles] || textStyle,
                };

                setTextItems([...textItems, newText]);
                setSelectedTextId(newText.id);
                setDrawerOpen(false);
              }
            }}
          >
            <div className="item-icon">📝</div>
            <div className="item-content">
              <div className="item-name">{item.name}</div>
              {item.category && (
                <div className="item-category">{item.category}</div>
              )}
            </div>
          </div>
        ))}
      </div>
    );
  };

  /**
   * 渲染抽屉内容
   */
  const renderDrawerContent = () => {
    if (!activeDrawer) return null;

    return (
      <div className="drawer-content-container">
        <Search
          placeholder={`搜索${activeDrawer}...`}
          allowClear
          enterButton="搜索"
          value={searchText}
          onChange={handleSearchChange}
          onSearch={handleSearch}
          className="drawer-search"
          loading={loading}
        />

        <div className="drawer-items-wrapper">
          {activeDrawer === "模板" ? (
            renderTemplateContent()
          ) : activeDrawer === "分享管理" ? (
            <div className="shared-images-container">
              <h3>已分享的图片</h3>
              {sharedImages.length === 0 ? (
                <div className="empty-message">暂无分享的图片</div>
              ) : (
                <Row gutter={[16, 16]} className="template-grid">
                  {sharedImages.map((image) => (
                    <Col span={12} key={image.id} className="template-col">
                      <div className="template-item">
                        <Image
                          src={image.img || undefined}
                          alt={image.title || "分享图片"}
                          preview={false}
                          className="template-image"
                          fallback="https://via.placeholder.com/150?text=图片加载失败"
                        />
                        <div className="template-info">
                          <div className="template-title" title={image.title}>
                            {image.title || `分享图片-${image.id}`}
                          </div>
                          {image.description && (
                            <div
                              className="template-description"
                              title={image.description}
                            >
                              {image.description}
                            </div>
                          )}
                          <div className="template-meta">
                            <button
                              className="unshare-button"
                              onClick={() => handleShareImage(image)}
                              style={{
                                background: '#ff4d4f',
                                color: 'white',
                                border: 'none',
                                padding: '4px 8px',
                                borderRadius: '4px',
                                cursor: 'pointer',
                                marginTop: '8px'
                              }}
                            >
                              取消分享
                            </button>
                          </div>
                        </div>
                      </div>
                    </Col>
                  ))}
                </Row>
              )}
            </div>
          ) : (
            renderTextDrawerContent()
          )}
        </div>
      </div>
    );
  };

  /**
   * 处理图片裁剪
   */
  const handleCrop = () => {
    if (cropperRef.current) {
      const cropper = cropperRef.current.cropper;
      const canvasData = cropper.getCroppedCanvas();
      const croppedImage = canvasData.toDataURL('image/png');
      
      // 更新选中的图片为裁剪后的图片
      setSelectedImage(croppedImage);
      setIsCropperVisible(false);
      
      // 重置图片尺寸和位置
      const img = new window.Image();
      img.onload = () => {
        setNaturalSize({
          width: img.width,
          height: img.height,
        });
        setImageSize({
          width: img.width,
          height: img.height,
        });
        // 重新计算居中位置
        if (canvasRef.current) {
          const rect = canvasRef.current.getBoundingClientRect();
          const centerX = (rect.width - img.width) / 2;
          const centerY = (rect.height - img.height) / 2;
          setImagePosition({
            x: Math.max(0, centerX),
            y: Math.max(0, centerY),
          });
        }
      };
      img.src = croppedImage;
    }
  };

  /**
   * 添加新文字
   */
  const handleAddText = () => {
    if (!textContent.trim()) return;

    const newText: TextItem = {
      id: Date.now().toString(),
      content: textContent,
      position: { x: 100, y: 100 }, // 默认位置
      style: { ...textStyle },
    };

    setTextItems([...textItems, newText]);
    setSelectedTextId(newText.id);
    setTextContent("");
    setIsAddingText(false);
  };

  /**
   * 更新文字样式
   */
  const handleTextStyleChange = (property: string, value: unknown) => {
    if (!selectedTextId) return;
    setTextItems(textItems => textItems.map(item => {
      if (item.id === selectedTextId) {
        return {
          ...item,
          style: {
            ...item.style,
            [property]: value,
          },
        };
      }
      return item;
    }));
    setTextStyle({
      ...textStyle,
      [property]: value,
    });
  };

  /**
   * 删除选中的文字
   */
  const handleDeleteText = () => {
    if (!selectedTextId) return;
    setTextItems(textItems.filter(item => item.id !== selectedTextId));
    setSelectedTextId(null);
  };

  // ========== 文字拖拽逻辑 ==========

  // 文字拖拽事件
  const handleTextMouseDown = (e: React.MouseEvent, textId: string) => {
    e.stopPropagation();
    setDraggingTextId(textId);
    // 计算鼠标点到文字左上角的偏移
    const textItem = textItems.find(t => t.id === textId);
    if (textItem) {
      setTextDragOffset({
        x: e.clientX - textItem.position.x,
        y: e.clientY - textItem.position.y,
      });
    }
    document.body.style.userSelect = "none";
  };

  const handleTextMouseMove = (e: React.MouseEvent) => {
    if (!draggingTextId) return;
    setTextItems(textItems => textItems.map(item => {
      if (item.id === draggingTextId) {
        return {
          ...item,
          position: {
            x: e.clientX - textDragOffset.x,
            y: e.clientY - textDragOffset.y,
          },
        };
      }
      return item;
    }));
  };

  const handleTextMouseUp = () => {
    setDraggingTextId(null);
    document.body.style.userSelect = "";
  };

  /**
   * 处理背景移除
   */
  const handleBackgroundRemoval = async () => {
    if (!selectedImage) return;

    try {
      setIsRemovingBackground(true);
      setRemovalProgress(0);
      // 保存原始图片，以便取消时恢复
      setOriginalImage(selectedImage);
      message.loading({ content: '正在移除背景...', key: 'removing' });
      
      // 模拟进度更新
      const progressInterval = setInterval(() => {
        setRemovalProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval);
            return prev;
          }
          return prev + 10;
        });
      }, 500);

      console.log('开始移除背景，图片URL:', selectedImage);
      
      // 将图片转换为PNG格式
      const img = new window.Image();
      img.crossOrigin = 'anonymous';
      
      // 等待图片加载
      await new Promise<void>((resolve, reject) => {
        img.onload = () => resolve();
        img.onerror = () => reject(new Error('图片加载失败'));
        img.src = selectedImage;
      });

      // 创建canvas并绘制图片
      const canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext('2d');
      if (!ctx) throw new Error('无法创建canvas上下文');
      
      ctx.drawImage(img, 0, 0);
      
      // 转换为PNG格式
      const pngImage = canvas.toDataURL('image/png');
      
      // 移除图像背景
      const blob = await removeBackground(pngImage);
      console.log('背景移除完成，生成blob:', blob);
      
      // 清除进度更新定时器
      clearInterval(progressInterval);
      setRemovalProgress(100);
      
      // 将Blob转换为data URL
      const reader = new FileReader();
      reader.onloadend = () => {
        const dataUrl = reader.result as string;
        console.log('转换完成，新的图片URL:', dataUrl);
        // 更新选中的图片为移除背景后的图片
        setSelectedImage(dataUrl);
        message.success({ content: '背景移除成功', key: 'removing' });
      };
      reader.onerror = (error) => {
        console.error('FileReader错误:', error);
        message.error({ content: '图片转换失败', key: 'removing' });
      };
      reader.readAsDataURL(blob);
      
    } catch (error) {
      console.error('背景移除失败:', error);
      message.error({ 
        content: `背景移除失败: ${error instanceof Error ? error.message : '未知错误'}`, 
        key: 'removing' 
      });
    } finally {
      setIsRemovingBackground(false);
      setRemovalProgress(0);
    }
  };

  /**
   * 取消背景移除
   */
  const handleCancelBackgroundRemoval = () => {
    if (originalImage) {
      setSelectedImage(originalImage);
      setOriginalImage(null);
      setRemovalProgress(0);
      message.info({ content: '已取消抠图', key: 'removing' });
    }
  };

  /**
   * 处理拖拽进入事件
   */
  const handleDragEnter = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDraggingOver(true);
  };

  /**
   * 处理拖拽离开事件
   */
  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDraggingOver(false);
  };

  /**
   * 处理拖拽悬停事件
   */
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  };

  /**
   * 处理拖拽放下事件
   */
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDraggingOver(false);

    const files = e.dataTransfer.files;
    if (files.length > 0) {
      const file = files[0];
      if (file.type.startsWith('image/')) {
        const reader = new FileReader();
        reader.onload = (event) => {
          if (event.target?.result) {
            setSelectedImage(event.target.result as string);
          }
        };
        reader.readAsDataURL(file);
      } else {
        message.error('请拖入图片文件');
      }
    }
  };

  /**
   * 处理图片下载
   * 将当前画布内容（包括图片和文字）导出为PNG图片
   */
  const handleDownload = async () => {
    if (!selectedImage) return;

    try {
      setIsDownloading(true);
      message.loading({ content: '正在生成图片...', key: 'downloading' });

      // 创建临时canvas
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      if (!ctx) return;

      // 设置canvas尺寸
      canvas.width = imageSize.width;
      canvas.height = imageSize.height;

      // 加载图片并处理跨域问题
      const img = new window.Image();
      img.crossOrigin = 'anonymous'; //用来设置跨域属性
      img.src = selectedImage;

      // 等待图片加载完成
      await new Promise((resolve, reject) => {
        img.onload = resolve;
        img.onerror = () => {
          reject(new Error('图片加载失败'));
        };
      });

      // 绘制图片
      ctx.drawImage(img, 0, 0, imageSize.width, imageSize.height);

      // 绘制所有文字
      textItems.forEach((textItem) => {
        ctx.save();
        ctx.font = `${textItem.style.fontStyle} ${textItem.style.fontWeight} ${textItem.style.fontSize}px ${textItem.style.fontFamily}`;
        ctx.fillStyle = textItem.style.color;
        ctx.textAlign = textItem.style.textAlign;
        ctx.globalAlpha = textItem.style.opacity;
        
        // 应用文字阴影
        if (textItem.style.shadow.blur > 0) {
          ctx.shadowColor = textItem.style.shadow.color;
          ctx.shadowBlur = textItem.style.shadow.blur;
          ctx.shadowOffsetX = textItem.style.shadow.offsetX;
          ctx.shadowOffsetY = textItem.style.shadow.offsetY;
        }

        // 应用文字描边
        if (textItem.style.stroke.width > 0) {
          ctx.strokeStyle = textItem.style.stroke.color;
          ctx.lineWidth = textItem.style.stroke.width;
          ctx.strokeText(
            textItem.content,
            textItem.position.x,
            textItem.position.y + textItem.style.fontSize
          );
        }

        // 绘制文字
        ctx.fillText(
          textItem.content,
          textItem.position.x,
          textItem.position.y + textItem.style.fontSize
        );
        ctx.restore();
      });

      try {
        // 尝试导出为PNG并下载
        canvas.toBlob((blob) => {
          if (blob) {
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `design-${Date.now()}.png`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            message.success({ content: '下载成功', key: 'downloading' });
          }
        }, 'image/png');
      } catch (error) {
        // 如果toBlob失败，尝试使用toDataURL
        const dataUrl = canvas.toDataURL('image/png');
        const a = document.createElement('a');
        a.href = dataUrl;
        a.download = `design-${Date.now()}.png`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        message.success({ content: '下载成功', key: 'downloading' });
      }

    } catch (error) {
      console.error('下载失败:', error);
      message.error({ content: '下载失败，请重试', key: 'downloading' });
    } finally {
      setIsDownloading(false);
    }
  };

  /**
   * 处理图片点击
   */
  const handleImageClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    setSelectedElement('image');
    setSelectedTextId(null);
  };

  /**
   * 处理画布点击
   */
  const handleCanvasClick = () => {
    setSelectedElement(null);
    setSelectedTextId(null);
  };

  // 处理图片分享
  const handleShareImage = (image: ImageItem) => {
    // 更新图片的分享状态
    const updatedImages = backendImages.map(img => {
      if (img.id === image.id) {
        return { ...img, isShared: !img.isShared };
      }
      return img;
    });
    setBackendImages(updatedImages);

    // 更新分享管理列表
    if (!image.isShared) {
      setSharedImages([...sharedImages, { ...image, isShared: true }]);
      message.success('图片已添加到分享管理');
    } else {
      setSharedImages(sharedImages.filter(img => img.id !== image.id));
      message.info('图片已从分享管理中移除');
    }
  };

  // ========== 主渲染方法 ==========
  return (
    <div className="main-container">
      {/* 左侧操作栏 */}
      <div className="left-sidebar">
        <button
          className={`sidebar-btn ${activeDrawer === "添加" ? "active" : ""}`}
          onClick={() => handleToggleDrawer("添加")}
          aria-label="添加元素"
        >
          <span className="btn-icon">➕</span>
          <span className="btn-text">添加</span>
        </button>

        <button
          className={`sidebar-btn ${activeDrawer === "模板" ? "active" : ""}`}
          onClick={() => handleToggleDrawer("模板")}
          aria-label="模板库"
        >
          <span className="btn-icon">📁</span>
          <span className="btn-text">模板</span>
        </button>

        <button
          className={`sidebar-btn ${activeDrawer === "元素" ? "active" : ""}`}
          onClick={() => handleToggleDrawer("元素")}
          aria-label="设计元素"
        >
          <span className="btn-icon">◇</span>
          <span className="btn-text">元素</span>
        </button>

        <button
          className={`sidebar-btn ${activeDrawer === "文字" ? "active" : ""}`}
          onClick={() => handleToggleDrawer("文字")}
          aria-label="文字工具"
        >
          <span className="btn-icon">A</span>
          <span className="btn-text">文字</span>
        </button>

        <button
          className={`sidebar-btn ${activeDrawer === "图片" ? "active" : ""}`}
          onClick={() => handleToggleDrawer("图片")}
          aria-label="图片库"
        >
          <span className="btn-icon">🖼️</span>
          <span className="btn-text">图片</span>
        </button>

        <button
          className={`sidebar-btn ${activeDrawer === "背景" ? "active" : ""}`}
          onClick={() => handleToggleDrawer("背景")}
          aria-label="背景设置"
        >
          <span className="btn-icon">🌈</span>
          <span className="btn-text">背景</span>
        </button>

        <button
          className={`sidebar-btn ${activeDrawer === "AI工具" ? "active" : ""}`}
          onClick={() => handleToggleDrawer("AI工具")}
          aria-label="AI工具"
        >
          <span className="btn-icon">🤖</span>
          <span className="btn-text">AI工具</span>
        </button>

        <button
          className={`sidebar-btn ${activeDrawer === "品牌" ? "active" : ""}`}
          onClick={() => handleToggleDrawer("品牌")}
          aria-label="品牌资产"
        >
          <span className="btn-icon">🏷️</span>
          <span className="btn-text">品牌</span>
        </button>

        <button
          className={`sidebar-btn ${activeDrawer === "团队" ? "active" : ""}`}
          onClick={() => handleToggleDrawer("团队")}
          aria-label="团队协作"
        >
          <span className="btn-icon">👥</span>
          <span className="btn-text">团队</span>
        </button>

        <button
          className={`sidebar-btn ${activeDrawer === "分享管理" ? "active" : ""}`}
          onClick={() => handleToggleDrawer("分享管理")}
          aria-label="分享管理"
        >
          <span className="btn-icon">📤</span>
          <span className="btn-text">分享管理</span>
        </button>

        <button
          className={`sidebar-btn ${activeDrawer === "我的" ? "active" : ""}`}
          onClick={() => handleToggleDrawer("我的")}
          aria-label="个人中心"
        >
          <span className="btn-icon">👤</span>
          <span className="btn-text">我的</span>
        </button>
      </div>

      {/* 中间主内容区 */}
      <div className={`middle-content ${drawerOpen ? "drawer-open" : ""}`} style={{ height: "100vh" }}>
        {/* 抽屉面板 */}
        <div className={`custom-drawer ${drawerOpen ? "open" : ""}`}>
          <div className="drawer-header">
            <h3 className="drawer-title">{activeDrawer} 面板</h3>
          </div>

          {renderDrawerContent()}

          <div
            className="drawer-toggle-btn"
            onClick={() => handleToggleDrawer(activeDrawer)}
            aria-label={drawerOpen ? "关闭抽屉" : "打开抽屉"}
          >
            <div className="arrow-icon"></div>
          </div>
        </div>

        {/* 页面主要内容 */}
        <div className="page-content" style={{ height: "100%" }}>
          <div
            className="canvas-area"
            onClick={handleCanvasClick}
            onMouseDown={handleDragStart}
            onMouseMove={e => { handleMouseMove(e); handleTextMouseMove(e); }}
            onMouseUp={() => { handleMouseUp(); handleTextMouseUp(); }}
            onMouseLeave={() => { handleMouseLeave(); handleTextMouseUp(); }}
            onDragEnter={handleDragEnter}
            onDragLeave={handleDragLeave}
            onDragOver={handleDragOver}
            onDrop={handleDrop}
            ref={canvasRef}
            style={{
              cursor: isDragging ? "grabbing" : selectedImage ? "grab" : "default",
              height: "100%",
              position: "relative",
              overflow: "visible",
              border: isDraggingOver ? "2px dashed #1890ff" : "none",
              backgroundColor: isDraggingOver ? "rgba(24, 144, 255, 0.1)" : "transparent",
              transition: "all 0.3s ease"
            }}
          >
            {selectedImage ? (
              <div
                onClick={handleImageClick}
                style={{
                  position: "absolute",
                  left: `${imagePosition.x}px`,
                  top: `${imagePosition.y}px`,
                  width: `${imageSize.width}px`,
                  height: `${imageSize.height}px`,
                  outline: selectedElement === 'image' ? "2px solid #1890ff" : "1px dashed #1890ff",
                  boxSizing: "border-box",
                  opacity: imageOpacity,
                }}
              >
                <img
                  src={selectedImage}
                  alt="选中的模板图片"
                  style={{
                    width: "100%",
                    height: "100%",
                    objectFit: "fill",
                    pointerEvents: "none",
                    display: "block",
                    opacity: imageOpacity,
                  }}
                  onLoad={handleImageLoad}
                  ref={imgElementRef}
                />
                {renderResizeHandles()}
                {/* 文字层：所有文字都渲染在图片容器内，位置相对于图片左上角 */}
                {textItems.map((textItem: TextItem) => {
                  let textStyle: React.CSSProperties = {
                    fontSize: textItem.style.fontSize,
                    fontFamily: textItem.style.fontFamily,
                    color: textItem.style.color,
                    fontWeight: textItem.style.fontWeight,
                    fontStyle: textItem.style.fontStyle,
                    textAlign: textItem.style.textAlign,
                    textDecoration: textItem.style.textDecoration,
                    letterSpacing: textItem.style.letterSpacing,
                    lineHeight: textItem.style.lineHeight,
                    opacity: textItem.style.opacity,
                    transform: `rotate(${textItem.style.rotate}deg)`,
                    textShadow: `${textItem.style.shadow.offsetX}px ${textItem.style.shadow.offsetY}px ${textItem.style.shadow.blur}px ${textItem.style.shadow.color}`,
                    WebkitTextStroke: `${textItem.style.stroke.width}px ${textItem.style.stroke.color}`,
                    position: "absolute",
                    left: `${textItem.position.x}px`,
                    top: `${textItem.position.y}px`,
                    cursor: draggingTextId === textItem.id ? "grabbing" : "move",
                    userSelect: "none",
                    outline: selectedTextId === textItem.id ? "2px solid #1890ff" : "none",
                    padding: "2px",
                  };
                  // 特效同原逻辑
                  switch (textItem.style.effect) {
                    case "glow":
                      textStyle = { ...textStyle, textShadow: `0 0 10px ${textItem.style.color}` };
                      break;
                    case "neon":
                      textStyle = { ...textStyle, textShadow: `0 0 5px ${textItem.style.color}, 0 0 10px ${textItem.style.color}, 0 0 20px ${textItem.style.color}` };
                      break;
                    case "metal":
                      textStyle = { ...textStyle, background: "linear-gradient(45deg, #808080, #ffffff)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent" };
                      break;
                    case "gradient":
                      textStyle = { ...textStyle, background: "linear-gradient(45deg, #ff0000, #00ff00, #0000ff)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent" };
                      break;
                    case "3d":
                      textStyle = { ...textStyle, textShadow: `1px 1px 0 #000,2px 2px 0 #000,3px 3px 0 #000,4px 4px 0 #000` };
                      break;
                  }
                  return (
                    <div
                      key={textItem.id}
                      style={textStyle}
                      onMouseDown={e => handleTextMouseDown(e, textItem.id)}
                      onClick={(e) => {
                        e.stopPropagation();
                        setSelectedElement('text');
                        setSelectedTextId(textItem.id);
                      }}
                    >
                      {textItem.content}
                    </div>
                  );
                })}
              </div>
            ) : (
              <>
                <h2>设计画布</h2>
                <p>拖拽左侧元素到此处进行设计</p>
                
                <p>或将图片文件拖入此处</p>
                <p>选中图片后可以拖拽和拖动边缘/角落缩放</p>
                <p>按住Shift键保持比例</p>
              </>
            )}
          </div>
        </div>
      </div>

      {/* 右侧属性面板 */}
      {/* 属性面板 */}
      <div className="right-content">
        <div className="property-panel">
          <h3>属性设置</h3>
          {selectedTextId ? (
            renderTextEditPanel()
          ) : isAddingText ? (
            <div className="add-text-panel">
              <div className="property-item">
                <label>输入文字</label>
                <Input.TextArea
                  value={textContent}
                  onChange={(e) => setTextContent(e.target.value)}
                  rows={3}
                  placeholder="请输入要添加的文字"
                />
              </div>

              <div className="property-item">
                <Button type="primary" onClick={handleAddText}>
                  添加文字
                </Button>
              </div>
            </div>
          ) : selectedImage ? (
            <>
              <div className="property-item">
                <label>尺寸</label>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <div>
                    <div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>宽度</div>
                    {isEditingWidth ? (
                      <Input
                        value={tempWidth}
                        onChange={handleWidthChange}
                        onBlur={submitWidthChange}
                        onKeyDown={(e) => handleKeyDown(e, "width")}
                        autoFocus
                        style={{ width: 80 }}
                        suffix="px"
                      />
                    ) : (
                      <Input
                        value={Math.round(imageSize.width)}
                        onClick={startEditingWidth}
                        readOnly
                        style={{ width: 80 }}
                        suffix="px"
                      />
                    )}
                  </div>
                  <div>
                    <div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>高度</div>
                    {isEditingHeight ? (
                      <Input
                        value={tempHeight}
                        onChange={handleHeightChange}
                        onBlur={submitHeightChange}
                        onKeyDown={(e) => handleKeyDown(e, "height")}
                        autoFocus
                        style={{ width: 80 }}
                        suffix="px"
                      />
                    ) : (
                      <Input
                        value={Math.round(imageSize.height)}
                        onClick={startEditingHeight}
                        readOnly
                        style={{ width: 80 }}
                        suffix="px"
                      />
                    )}
                  </div>
                </div>
              </div>
              <div className="property-item">
                <label>位置</label>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <div>
                    <div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>X</div>
                    <Input
                      value={Math.round(imagePosition.x)}
                      readOnly
                      style={{ width: 80 }}
                      suffix="px"
                    />
                  </div>
                  <div>
                    <div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>Y</div>
                    <Input
                      value={Math.round(imagePosition.y)}
                      readOnly
                      style={{ width: 80 }}
                      suffix="px"
                    />
                  </div>
                </div>
              </div>
                  <div className="property-item">
                    <button
                      onClick={() => setIsCropperVisible(true)}
                      style={{
                        padding: "4px 8px",
                        background: "#1890ff",
                        color: "white",
                        border: "none",
                        borderRadius: "4px",
                        cursor: "pointer",
                        marginBottom: "8px"
                      }}
                    >
                      裁剪图片
                    </button>
                  </div>
              <div className="property-item">
                <button
                  onClick={handleBackgroundRemoval}
                  disabled={isRemovingBackground}
                  style={{
                    padding: "4px 8px",
                    background: "#1890ff",
                    color: "white",
                    border: "none",
                    borderRadius: "4px",
                    cursor: isRemovingBackground ? "not-allowed" : "pointer",
                    marginBottom: "8px",
                    opacity: isRemovingBackground ? 0.5 : 1
                  }}
                >
                  {isRemovingBackground ? "正在移除背景..." : "抠图"}
                </button>
                {isRemovingBackground && (
                  <>
                    <div style={{ marginBottom: "8px" }}>
                      <div style={{ 
                        width: "100%", 
                        height: "4px", 
                        background: "#f0f0f0", 
                        borderRadius: "2px",
                        overflow: "hidden"
                      }}>
                        <div style={{
                          width: `${removalProgress}%`,
                          height: "100%",
                          background: "#1890ff",
                          transition: "width 0.3s ease"
                        }} />
                      </div>
                      <div style={{ 
                        fontSize: "12px", 
                        color: "#666", 
                        textAlign: "right", 
                        marginTop: "4px" 
                      }}>
                        {removalProgress}%
                      </div>
                    </div>
                    <button
                      onClick={handleCancelBackgroundRemoval}
                      style={{
                        padding: "4px 8px",
                        background: "#ff4d4f",
                        color: "white",
                        border: "none",
                        borderRadius: "4px",
                        cursor: "pointer",
                        marginBottom: "8px",
                        marginLeft: "8px"
                      }}
                    >
                      取消抠图
                    </button>
                  </>
                )}
              </div>
                  <div className="property-item">
                    <button
                      onClick={resetImage}
                      style={{
                        padding: "4px 8px",
                        background: "#1890ff",
                        color: "white",
                        border: "none",
                        borderRadius: "4px",
                        cursor: "pointer",
                      }}
                    >
                      重置位置和大小
                    </button>
                  </div>
              <div className="property-item">
                <label>图片透明度</label>
                <Slider
                  min={0}
                  max={1}
                  step={0.01}
                  value={imageOpacity}
                  onChange={setImageOpacity}
                />
              </div>
              <div className="property-item">
                <label>原始尺寸</label>
                <Input
                  value={naturalSize.width}
                  readOnly
                  style={{ width: 80 }}
                  suffix="px"
                />
                <Input
                  value={naturalSize.height}
                  readOnly
                  style={{ width: 80 }}
                  suffix="px"
                />
              </div>
              <div className="property-item">
                <button
                  onClick={handleDownload}
                  disabled={isDownloading}
                  style={{
                    padding: "4px 8px",
                    background: "#1890ff",
                    color: "white",
                    border: "none",
                    borderRadius: "4px",
                    cursor: isDownloading ? "not-allowed" : "pointer",
                    opacity: isDownloading ? 0.5 : 1,
                    width: "100%"
                  }}
                >
                  {isDownloading ? "正在生成图片..." : "下载设计"}
                </button>
              </div>
            </>
          ) : (
            <div className="empty-state">
              <p>请选择图片或文字进行编辑</p>
            </div>
          )}
        </div>
      </div>

      {/* 裁剪模态框 */}
      <Modal
        title="裁剪图片"
        open={isCropperVisible}
        onOk={handleCrop}
        onCancel={() => setIsCropperVisible(false)}
        width={800}
        okText="确认裁剪"
        cancelText="取消"
      >
        <div style={{ height: 400 }}>
          <Cropper
            ref={cropperRef}
            src={selectedImage || ''}
            style={{ height: 400, width: '100%' }}
            aspectRatio={NaN}
            guides={true}
            autoCrop={true}
            viewMode={1}
            dragMode="move"
            cropBoxMovable={true}
            cropBoxResizable={true}
            background={true}
            responsive={true}
            restore={false}
            center={true}
            highlight={true}
            zoomable={true}
            zoomOnTouch={true}
            zoomOnWheel={true}
            toggleDragModeOnDblclick={true}
          />
        </div>
      </Modal>
    </div>
  );
};

export default Createdesign;